package com.hao.statussheet.utils;

import android.media.MediaPlayer;
import android.media.TimedMetaData;
import android.media.TimedText;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;

import com.hao.statussheet.bean.MusicBean;
import com.hao.statussheet.handler.ServiceSendActivityHandler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by hao on 16/12/4.
 */
public class PlayerUtils {

    private static final String TAG = PlayerUtils.class.getSimpleName();

    private MediaPlayer mediaPlayer;

    private MusicBean startMusicBean;

    private OnPlayStopListener onPlayStopListener;

    private OnPlayStartListener onPlayStartListener;

    private Date date;
    private SimpleDateFormat simpleDateFormat;

    private int nowPosition = 0;


    /**
     * 初始化数据
     */
    public PlayerUtils() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(onBufferingUpdateListener);
        mediaPlayer.setOnCompletionListener(onCompletionListener);
        mediaPlayer.setOnErrorListener(onErrorListener);
        mediaPlayer.setOnInfoListener(onInfoListener);
        mediaPlayer.setOnTimedTextListener(onTimedTextListener);
        mediaPlayer.setOnTimedMetaDataAvailableListener(onTimedMetaDataAvailableListener);
        mediaPlayer.setOnVideoSizeChangedListener(onVideoSizeChangedListener);
        mediaPlayer.setOnSeekCompleteListener(onSeekCompleteListener);
        mediaPlayer.setOnPreparedListener(onPreparedListener);
    }

    /**
     * 设置播放数据
     *
     * @param musicBean
     */
    public void setDataSource(MusicBean musicBean) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(musicBean.getMusicUrl());
            mediaPlayer.prepare();
            startMusicBean = musicBean;
            nowPosition = PalyListUtils.getMusicBeanList().indexOf(startMusicBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 切换播放源
     *
     * @param musicBean
     */
    public void switchDataSource(MusicBean musicBean) {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        setDataSource(musicBean);
    }

    /**
     * 左右切换的操作
     *
     * @param isStatus
     */
    public void life0rRieght(boolean isStatus) {
        if (isStatus) {
            if (nowPosition <= 0)
                return;
            MusicBean musicBean = PalyListUtils.getMusicBeanList().get(nowPosition - 1);
            switchDataSource(musicBean);
        } else {
            if (nowPosition >= PalyListUtils.getSize() - 1)
                return;
            MusicBean musicBean = PalyListUtils.getMusicBeanList().get(nowPosition + 1);
            switchDataSource(musicBean);
        }
    }

    /**
     * 暂停播放
     */
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }

    /**
     * 停止播放
     */
    public void stop() {
        mediaPlayer.stop();
        mediaPlayer.release();

        Message message = ServiceSendActivityHandler.obtainMessage();
        message.what = ServiceSendActivityHandler.ON_STOP;
        ServiceSendActivityHandler.getHandler().sendMessage(message);

    }

    /**
     * 跳转到指定的位置 这里直接传入seek值就好, 进度条总长确定为100
     *
     * @param seek
     * @return 返回的是true 为设置成功,返回的是false 为设置失败
     */
    public boolean seekTo(int seek) {
        if (mediaPlayer.isPlaying()) {
            int msec = seek / 100 * mediaPlayer.getDuration();
            mediaPlayer.seekTo(msec);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 据需播放
     */
    public void play() {
        if (!mediaPlayer.isPlaying())
            mediaPlayer.start();
    }

    /**
     * 判断是不是在播放中
     *
     * @return
     */
    public boolean isPlaying() {
        try {
            return mediaPlayer.isPlaying();
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 获取播放的时间
     *
     * @return
     */
    public String getPlayTime() {
        int position = mediaPlayer.getCurrentPosition();
        if (position > 0) {
            if (date == null)
                date = new Date(position);
            else date.setTime(position);
            if (simpleDateFormat == null)
                simpleDateFormat = new SimpleDateFormat("mm:ss");
            String time = simpleDateFormat.format(date);
            return time;
        } else {
            return "00:00";
        }
    }

    /**
     * 返回播放的进度值 , 这里处理视为总长100
     *
     * @return
     */
    public int getPlayCurrent() {
        int position = mediaPlayer.getCurrentPosition();
        int duration = mediaPlayer.getDuration();
        return position * 100 / duration;
    }

    /**
     * 准备播放
     */
    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            Log.i(TAG, ">>>onPrepared>>>>>>>>");
            onPlayStartListener.onPlayStart();
        }
    };

    /**
     * 单个音乐播放完成以后的处理
     */
    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, ">>>onCompletion>>>>>>>>");
            int oldPosition = PalyListUtils.getMusicBeanList().indexOf(startMusicBean);
            if (oldPosition >= PalyListUtils.getSize() - 1) {
                stop();
                PalyListUtils.clear();
                onPlayStopListener.onPlayStop();
            } else {
                startMusicBean.setStatus(PalyStatus.STOP);
                MusicBean musicBean = PalyListUtils.getMusicBeanList().get(oldPosition + 1);
                musicBean.setStatus(PalyStatus.PROGRESS);
                switchDataSource(musicBean);
                play();
            }
        }
    };

    /**
     * 缓冲状态的监听
     */
    private MediaPlayer.OnBufferingUpdateListener onBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            Log.i(TAG, ">>>onBufferingUpdate>>>>>>>>");
            Log.i(TAG, ">>>onBufferingUpdate>>>>percent>>>>" + percent);
        }
    };

    private MediaPlayer.OnSeekCompleteListener onSeekCompleteListener = new MediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(MediaPlayer mp) {
            Log.i(TAG, ">>>onSeekComplete>>>>>>>>");
        }
    };

    private MediaPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
            Log.i(TAG, ">>>onVideoSizeChanged>>>>>>>>");
            Log.i(TAG, ">>>onVideoSizeChanged>>>width>>>>>" + width);
            Log.i(TAG, ">>>onVideoSizeChanged>>>>height>>>>" + height);
        }
    };

    private MediaPlayer.OnTimedTextListener onTimedTextListener = new MediaPlayer.OnTimedTextListener() {
        @Override
        public void onTimedText(MediaPlayer mp, TimedText text) {
            Log.i(TAG, ">>>onTimedText>>>>>>>>");
            Log.i(TAG, ">>>onTimedText>>>text>>>>>" + text);
        }
    };

    private MediaPlayer.OnTimedMetaDataAvailableListener onTimedMetaDataAvailableListener = new MediaPlayer.OnTimedMetaDataAvailableListener() {
        @Override
        public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data) {
            Log.i(TAG, ">>>onTimedText>>>>>>>>");
            Log.i(TAG, ">>>onTimedText>>>>>data.getMetaData()>>>" + data.getMetaData().toString());
            Log.i(TAG, ">>>onTimedText>>>>>data.getTimestamp()>>>" + data.getTimestamp());
        }
    };

    private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.i(TAG, ">>>onError>>>>>>>>");
            Log.i(TAG, ">>>onError>>>>what>>>>" + what);
            Log.i(TAG, ">>>onError>>>>extra>>>>" + extra);
            return true;
        }
    };

    private MediaPlayer.OnInfoListener onInfoListener = new MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            Log.i(TAG, ">>>onInfo>>>>>>>>");
            Log.i(TAG, ">>>onInfo>>>>what>>>>" + what);
            Log.i(TAG, ">>>onInfo>>>extra>>>>>" + extra);
            return true;
        }
    };

    public void setOnPlayStopListener(OnPlayStopListener onPlayStopListener) {
        this.onPlayStopListener = onPlayStopListener;
    }

    public void setOnPlayStartListener(OnPlayStartListener onPlayStartListener) {
        this.onPlayStartListener = onPlayStartListener;
    }

    /**
     * 播放结束的回调
     */
    public interface OnPlayStopListener {
        void onPlayStop();
    }

    /**
     * 播放开始的回调
     */
    public interface OnPlayStartListener {
        void onPlayStart();
    }
}
